#pragma once

#include <iostream>
#include <memory>
#include <unistd.h>
#include <algorithm>
#include "Socket.hpp"
#include "Log.hpp"

using namespace LogModule;
using namespace SocketModule;

class SelectServer
{
    const static int size = sizeof(fd_set) * 8;
    const static int defaultfd = -1;

public:
    SelectServer(int port)
        :_listenSockFd(std::make_unique<TcpSocket>())
        ,_isrunning(false)
    {
        _listenSockFd->BuildTcpSocketMethod(port);
        for(int i = 0; i < size; i++)
            _fd_arr[i] = defaultfd;

            _fd_arr[0] = _listenSockFd->Fd();
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            fd_set rfds;
            FD_ZERO(&rfds);
            int maxfd = defaultfd;
            for(int i = 0; i < size; i++)
            {
                if(_fd_arr[i] == defaultfd)
                    continue;
                
                FD_SET(_fd_arr[i], &rfds);
                maxfd = std::max(maxfd, _fd_arr[i]);
            }
            //PrintFd();
            int res = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);

            switch(res)
            {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::INFO) << "time out...";
                break;
            default:
                LOG(LogLevel::DEBUG) << "Event ready..." << res;
                Dispatcher(rfds);
                break;
            }
        }
        
        _isrunning = false;
    }

    void Dispatcher(fd_set& rfds)
    {
        //处理实际读事件就绪的套接字
        //读事件就绪包括监听套接字有连接到来，普通套接字客户端发来新消息
        for(int i = 0; i < size; i++)
        {
            if(_fd_arr[i] == defaultfd)
                continue;
            if(FD_ISSET(_fd_arr[i], &rfds))
            {
                //需要区分是新连接到来还是普通客户端发来信息
                if(_fd_arr[i] == _listenSockFd->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(_fd_arr[i], i);    
                }
            }
        }
    }

    void Accepter()
    {
        InetAddr client;
        int sockfd = _listenSockFd->Accept(&client);
        if(sockfd >= 0)
        {
            int pos = 0;
            while(pos < size)
            {
                if(_fd_arr[pos] == defaultfd)
                    break;
                pos++;
            }

            if(pos == size)
            {
                LOG(LogLevel::WARNING) << "select server full";
                close(sockfd);
            }
            else
            {
                _fd_arr[pos] = sockfd;
            }
        }
    }

    void Recver(int fd, int pos)
    {
        char buffer[1024];
        ssize_t n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        //这里读取的报文需要http协议处理
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say@ "<< buffer << std::endl;
        }
        else if(n == 0)
        {
            LOG(LogLevel::INFO) << "clien quit...";
            _fd_arr[pos] = defaultfd;
            close(fd);
        }

    }

    void Stop()
    {
        _isrunning = false;
    }

    void PrintFd()
    {
        std::cout << "_fd_arr[]: ";
        for(int i = 0; i < size; i++)
        {
            if(_fd_arr[i] == defaultfd)
                continue;
            std::cout << _fd_arr[i] << " ";
        }
        std::cout << std::endl;
    }

private:
    std::unique_ptr<Socket> _listenSockFd;
    bool _isrunning;

    int _fd_arr[size];
};